package com.qmgyl.marketshop.stock.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.qmfresh.service.shop.facade.dto.InstockQuery;
import com.qmfresh.service.shop.facade.dto.ShopTimeQuery;
import com.qmgyl.marketshop.api.ServiceApi;
import com.qmgyl.marketshop.api.StockServiceApi;
import com.qmgyl.marketshop.common.HttpUtils;
import com.qmgyl.marketshop.vo.ListWithPage;
import com.qmgyl.marketshop.vo.ProcurementOrderInstock;
import com.qmgyl.marketshop.vo.ProcurementOrderInstockItem;
import com.qmgyl.marketshop.vo.ProcurementOrderInstockResult;
import com.qmgyl.marketshop.vo.ProcurementOrderItem;


import util.DateUtils;
import util.ExcelUtil_Extend;
import util.JsonUtil;
import util.Page;
import util.Torder;

@Controller
@RequestMapping(value = "/shop/stock")
public class StockController {
	
	@Autowired
	private StockServiceApi serviceApi;

	
	@RequestMapping(value="/{name}", method = RequestMethod.GET)
	public String order(@PathVariable("name") String name){
		return "stock/"+name;
	}
	
	
	
	/**
	 * 获取入库单列表
	 * @param page
	 * @param rows
	 * @param ssuName
	 * @param className
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "getIndex")
	@ResponseBody
	public void getIndex(Integer page,Integer rows,Date s_time,Date e_time,Long procerementId,Integer InstockId,HttpServletRequest request, HttpServletResponse response) throws IOException{
try {
	
	ShopTimeQuery shopTimeQuery=new ShopTimeQuery();
	shopTimeQuery.setPage(page);
	shopTimeQuery.setSize(rows);
	if(s_time!=null&&e_time!=null){
		shopTimeQuery.setStartTime(new Long(s_time.getTime()).intValue()/1000);
		shopTimeQuery.setEndTime(new Long(e_time.getTime()).intValue()/1000);
	}
	if(procerementId!=null){
		shopTimeQuery.setProcurementId(procerementId);
	}
	if(InstockId!=null){
		shopTimeQuery.setInstockId(InstockId);
	}
	ListWithPage<ProcurementOrderInstockResult> listWithPage=serviceApi.getList(shopTimeQuery);
	List<ProcurementOrderInstockResult> procurementOrderInstockResults=listWithPage.getListData();
	List<Map<String,Object>> lis=new ArrayList<Map<String,Object>>();
	for(ProcurementOrderInstockResult pro:procurementOrderInstockResults){
		Map<String,Object> ma=new HashMap<String,Object>();
		ma.put("id",pro.getProcurementOrderInstock().getId());
		ma.put("procerementId", pro.getProcurementOrderInstock().getProcerementId());
		long time=pro.getProcurementOrderInstock().getCt().intValue()*1000L;
		ma.put("ct",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time)));//js.getOrderMain().getcT()
		ma.put("shopName", pro.getShopName());
		lis.add(ma);
	}
	Map<String,Object> map=new HashMap<String,Object>();
	map.put("total", listWithPage.getTotalCount());
	map.put("rows", lis);
	/*Page pages=new Page();
	pages.setResultList(lis);
	pages.setStart((page-1)*rows);
	pages.setTotalSize(listWithPage.getTotalCount());
	pages.setPageSize(rows);*/
	response.setContentType("application/json;charset=UTF-8");
	response.getWriter().write(JSONObject.toJSONString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 入库单详情
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value = "instockDetail")
	public String instockDetail(Integer id,HttpServletRequest req, HttpServletResponse res) {
		ShopTimeQuery shopTimeQuery=new ShopTimeQuery();
		if(id!=null){
			shopTimeQuery.setInstockId(id);
			shopTimeQuery.setPage(1);
			shopTimeQuery.setSize(1);
		}
		ListWithPage<ProcurementOrderInstockResult> listWithPage=serviceApi.getList(shopTimeQuery);
		List<ProcurementOrderInstockResult> procurementOrderInstockResults=listWithPage.getListData();
		req.setAttribute("procurementOrderInstock", procurementOrderInstockResults.get(0).getProcurementOrderInstock());
		List<ProcurementOrderInstockItem> list=procurementOrderInstockResults.get(0).getProcurementOrderInstockItems();
		for(ProcurementOrderInstockItem pro:list){
			pro.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(pro.getInstockTime()*1000L)));
		}
		req.setAttribute("procurementOrderInstockItems",list);
		req.setAttribute("shopName", procurementOrderInstockResults.get(0).getShopName());
		req.setAttribute("instockTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(procurementOrderInstockResults.get(0).getProcurementOrderInstock().getCt()*1000L)));
		return "stock/instock_detail";
	}
	

	/**
	 * 新增入库单
	 * @param req
	 * @param res
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "add")
	public String detail(String id,String procurementOrderId,HttpServletRequest req, HttpServletResponse res) {
		req.setAttribute("id", id);
		req.setAttribute("procurementOrderId", procurementOrderId);
		if(id!=null&&!"".equals(id)){
			req.setAttribute("title", "入库单修改");
		}else{
			req.setAttribute("title", "入库单新建");
		}
		return "stock/add";
	}
	
	/**
	 *  入库item
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value="getItem")
	@ResponseBody
	public void getItem(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
		ShopTimeQuery shopTimeQuery=new ShopTimeQuery();
		if(id!=null){
			shopTimeQuery.setInstockId(id);
			shopTimeQuery.setPage(1);
			shopTimeQuery.setSize(1);
		}

		ListWithPage<ProcurementOrderInstockResult> listWithPage=serviceApi.getList(shopTimeQuery);
		List<ProcurementOrderInstockResult> procurementOrderInstockResults=listWithPage.getListData();
		request.setAttribute("procurementOrderInstock", procurementOrderInstockResults.get(0).getProcurementOrderInstock());
		List<ProcurementOrderInstockItem> list=procurementOrderInstockResults.get(0).getProcurementOrderInstockItems();
		List<Object> li = new ArrayList<>();
		for(ProcurementOrderInstockItem pro:list){
			pro.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(pro.getInstockTime()*1000L)));
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("id",pro.getId()); 
			data.put("skuName",pro.getSkuName()); 
			data.put("skuFormat", pro.getSkuFormat());
			data.put("weight",pro.getWeight());
			data.put("num", pro.getNum());
			data.put("time",pro.getTime());	
			data.put("procurementOrderItemId",pro.getProcurementOrderItemId());	
			li.add(data);
		}
		request.setAttribute("shopName", procurementOrderInstockResults.get(0).getShopName());
		request.setAttribute("instockTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(procurementOrderInstockResults.get(0).getProcurementOrderInstock().getCt()*1000L)));
	/*	Page pages=new Page();
		pages.setResultList(li);
		pages.setStart(1);
		pages.setTotalSize(10);
		pages.setPageSize(10);*/
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("total", listWithPage.getTotalCount());
		map.put("rows", li);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value="changeItem")
	@ResponseBody
	public String changeItem(Long id,String weight,Integer num,HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
		InstockQuery instockQuery=new InstockQuery();
		instockQuery.setId(id);
		instockQuery.setWeight(new BigDecimal(weight));
		instockQuery.setNum(num);
		String result=serviceApi.changeItem(instockQuery);
		return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	@RequestMapping(value="getNeedInstock",produces="text/html;charset=UTF-8;")
	@ResponseBody
	public String getNeedInstock(Long procurementId,HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
		InstockQuery instockQuery=new InstockQuery();
		instockQuery.setProcurementId(procurementId);
		List<ProcurementOrderItem> result=serviceApi.getNeedInstock(instockQuery);
		String res=JsonUtil.getJsonString4List(result);
		return res;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value="createStock",produces="text/html;charset=UTF-8;")
	@ResponseBody
	public String createStock(Long procurementId,String weight,Integer num,Long  procurementOrderItemId,HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
		InstockQuery instockQuery=new InstockQuery();
		instockQuery.setProcurementId(procurementId);
		instockQuery.setNum(num);
		instockQuery.setWeight(new BigDecimal(weight));
		instockQuery.setProcurementOrderItemId(procurementOrderItemId);
		String result = serviceApi.createStock(instockQuery);
		return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 导出入库单
	 * 
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "exportStockOrder")
	@ResponseBody
	public String exportStockOrder(Long procurementId,HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		// 配送数据
		List<List<String>> dataList = new ArrayList<List<String>>();
		ShopTimeQuery shopTimeQuery=new ShopTimeQuery();
		if(procurementId!=null){
			shopTimeQuery.setProcurementId(procurementId);
			shopTimeQuery.setPage(1);
			shopTimeQuery.setSize(1);
		}
		ListWithPage<ProcurementOrderInstockResult> listWithPage=serviceApi.getList(shopTimeQuery);
		List<ProcurementOrderInstockResult> procurementOrderInstockResults=listWithPage.getListData();
		List<Map<String,Object>> lis=new ArrayList<Map<String,Object>>();
			Map<String,Object> ma=new HashMap<String,Object>();
			ProcurementOrderInstockResult js=procurementOrderInstockResults.get(0);
			List<ProcurementOrderInstockItem> procurementOrderInstockItems=js.getProcurementOrderInstockItems();
			for(ProcurementOrderInstockItem p:procurementOrderInstockItems){
				List<String> rowList = new ArrayList<String>();
				rowList.add(p.getProcurementOrderItemId()+"");
				rowList.add(p.getSkuName());
				rowList.add(p.getSkuFormat());
				rowList.add(p.getWeight()+"");
				rowList.add(p.getNum()+"");
				rowList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(p.getInstockTime()*1000L)));
				dataList.add(rowList);
			}
			lis.add(ma);
		String fileName = "instock_order_" + DateUtils.getYYYY_MM_DD()+"_"+js.getProcurementOrderInstock().getId()+ ".xls";
		String[] head = { "对应采购单行ID","商品名称", "商品规格", "重量", "入库数量", "入库时间"};
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("出库单");
		sheet.setColumnWidth(0, 8000);
		sheet.setColumnWidth(5, 18000);
		ExcelUtil_Extend.createExcelMerge(workbook, sheet, "出库单", head,
				dataList, false, null, null, null, null);

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 将excel写入流
		workbook.write(byteArrayOutputStream);
		ExcelUtil_Extend.exportExelMerge(res, byteArrayOutputStream, fileName);

		return fileName;

	}
	
	/**
	 * 日期格式数据绑定
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		sf.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sf, true));
	}
}
